package handler

import (
	"bytes"
	"encoding/json"
	"fmt"
	amodel "funlog-gserver/model/api"
	esdb "funlog-gserver/stored/es"
	qqwry "funlog-gserver/stored/qqwry"
	"io"
	"log" //互斥锁需要使用这个包。
	"time"

	"github.com/nsqio/go-nsq"
)

func DoMessage(msg *nsq.Message) (err error) {
	// fmt.Println(msg.NSQDAddress, string(msg.Body))

	// res, err := es.Create("demo", "esd", &buf, es.Create.WithDocumentType("doc"))
	var logJson amodel.LogInfo
	var error error
	if error = json.Unmarshal(msg.Body, &logJson); error != nil {
		return error
	}
	if logJson.AuthInfo.IPAddr != "" {
		logJson.AuthInfo.Addr = qqwry.GetAddrByIp(logJson.AuthInfo.IPAddr)
	}
	logJson.AuthInfo.CreateAt = time.Now()
	var logBytes []byte
	if logBytes, error = json.Marshal(logJson); error != nil {
		return error
	}

	buf := bytes.NewBuffer(logBytes) //使用New返回Buffer变量
	// println(buf.String())
	res, err := esdb.ESClient.Index(fmt.Sprintf("funlog-%s", time.Now().Format("2006.01-02")), buf)
	if err != nil {
		// failOnError(err, "Error Index response")
		log.Printf("Error Index response", err)
	}
	body, _ := io.ReadAll(res.Body)
	if res.StatusCode >= 400 {
		log.Printf("Error Index response", string(body))
	}
	defer res.Body.Close()
	return
}
